package com.xinwei.leetcode.数组;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

// https://leetcode-cn.com/problems/intersection-of-two-arrays/
public class _349_两个数组的交集 {
    // 用hashset  --> 失败
    public int[] intersection(int[] nums1, int[] nums2) {
        HashSet<Integer> set = new HashSet<>(nums1.length);
        int[] nums3 = new int[Math.min(nums1.length, nums2.length)];
        int a = 0;
        for (int i = 0; i < nums1.length; i++) {
            set.add(nums1[i]);
        }
        for (int i = 0; i < nums2.length; i++) {
            if (set.contains(nums2[i])) {
                nums3[a] = nums2[i];
                a++;
                set.remove(nums2[i]);
            }
        }
        return nums3;
    }

    // 用hashmap 遍历两个数组，记录出现的次数
    public int[] intersection2(int[] nums1, int[] nums2) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums1.length; i++) {
            map.put(nums1[i], 1);
        }
        int a = 0;// 用来记录重复的数的数量
        for (int i = 0; i < nums2.length; i++) {
            if (map.containsKey(nums2[i])) {
                if (map.get(nums2[i]) == 1) {
                    a++;
                }
                map.put(nums2[i], 2);
            }
        }
        int[] nums = new int[a];
        a = 0;
        for (Integer integer : map.keySet()) {
            if (map.get(integer) == 2) {
                nums[a] = integer;
                a++;
            }
        }
        return nums;
    }
}
